<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="35%"
    >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
            <el-form-item label="条码" prop="code" >
                <el-input v-model="createForm.code" type="textarea" autosize style="width: 150px"/>
            </el-form-item>
            <el-form-item label="点检内容" prop="content" >
                <el-input v-model="createForm.content" type="textarea" autosize style="width: 300px"/>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >新增</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->

      <!-- <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.workCenter"
            placeholder="工作中心"
        ></el-input> -->

        <el-select
            v-model="param.workCenter" 
            clearable
            filterable
            style="margin-right: 10px;width: 120px"
             @focus="getDepartInfo"
            placeholder="请选择工作中心"
            class="ul-item">
            <el-option :value="item" :label="item" v-for="(item,index) in this.workCenterList" :key="index"/>
        </el-select>

        <el-select 
            v-model="param.problemLink" 
            clearable
            filterable
            style="margin-right: 10px;width: 120px"
            placeholder="请先择检验环节"
            class="ul-item">
            <el-option :value="item" :label="item" v-for="(item,index) in this.problemLinkList" :key="index"/>
        </el-select>

        <!-- <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.problemLink"
            placeholder="检验环节"
        ></el-input> -->

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.technologyNo"
            placeholder="品号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.clientNumber"
            placeholder="客户编码"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px"
            :style="{ width: inputWid(param.deviceBarcode) }"
            v-model="param.deviceBarcode"
            placeholder="产品条码"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.workOrderNo"
            placeholder="工单号码"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 10px;width: 120px"
            v-model="param.result"
            placeholder="检查结果"
        ></el-input>

        <el-date-picker
          v-model="dateOptions"
           style="width: 340px"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="内容"  prop="context" align="center"/>
      <el-table-column label="检验环节"  prop="problemLink" align="center"/> 
      <el-table-column label="产品品号"  prop="technologyNo" align="center"/>
      <el-table-column label="客户编码"  prop="clientNumber" align="center"/>
      <el-table-column label="工单号码"  prop="workOrderNo" align="center"/>
      <el-table-column label="产品条码"  prop="deviceBarcode" align="center"/>
      <el-table-column label="检查结果"  prop="result" align="center"/>
      <el-table-column label="检查人"  prop="jobNumber" align="center"/>
      <el-table-column label="确认人"  prop="confirmor" align="center"/>
      <el-table-column label="检查表附件"  prop="accessory" align="center"/>
      <el-table-column label="拍照记录"  prop="img" align="center">
        <template slot-scope="scope">
            <el-image v-for="(item, index) in scope.row.img" :key='index' style="width: 30px; height: 30px" :src="item" :preview-src-list="scope.row.img" fit="scale-down">
                <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                </div>
            </el-image>
        </template>
      </el-table-column>
      <el-table-column label="检查日期"  prop="createTime" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="hExportExcel('XZ',scope.row)">下载</el-button>
                    <el-button
                        v-if="userInfo.roleId == 14"
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="修改工序信息"
      :visible.sync="showupd"
      @close="showupd = false"
      width="35%"
    >
        <el-form :inline="true" :model="updForm" ref="updForm" :rules="addRules">
            <el-form-item label="条码" prop="code" >
                <el-input v-model="updForm.code" type="textarea" autosize  style="width: 150px"/>
            </el-form-item>
            <el-form-item label="点检内容" prop="content" >
                <el-input v-model="updForm.content" type="textarea" autosize style="width: 300px"/>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')"
            >修改</el-button
            >
        </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel('ALL')">导出数据Excel</el-button>

  </div>
</template>

<script>
import { configurationAdd,configurationUpd } from "@/api/processRoute"
import { inspectionRecordFind,inspectionRecordDel } from "@/api/checkSetting"
import { getDepartList } from '@/api/user'
export default {
    name: 'inspectionRecord',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                code: '',                      
                content: ''                    
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                code: [
                    { required: true, message: "条码不能为空!", trigger: "change" },
                ],
                content: [
                    { required: true, message: "点检内容不能为空!", trigger: "change" },
                ],
            },
            dateOptions: this.getNowTime(),
            pickerOptions: {                            // 选择时间范围
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            accessTypeList: ['出库','入库'],
            barcodeType3List: [],
            workCenterList:[],
            problemLinkList:['新员工检查','FQC检验','开线确认','OQC检验','OBA检验']
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        // 获取部门函数
    async getDepartInfo() {
        let {data} = await getDepartList()
        this.workCenterList = data
    },
      // 切割图片url组成的字符串成为数组
      cuttingStr(value) {
          console.log(value)
            let imageArr = []                           //存储图片url的数组
            if(value != '' && value != null) {                           //第一层嵌套判断是否有图片，为空直接返回一个空数组
                if(value.includes('|')){
                  imageArr = value.split('|')             //第二层嵌套将图片拆分为数组
                } else{
                  imageArr.push(value)
                }
                return imageArr
            } else {
                return imageArr
            }
        },
            //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
      getNowTime() {
        let dateTime = +new Date()+8*3600*1000
        const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10) //默认开始时间7天前
        const end = new Date(dateTime)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10)//默认结束时间当前时间
        console.log([start, end])
        return [start, end]
        },
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
            if(this.param.problemLink){ query.problemLink = this.param.problemLink}
            if(this.param.technologyNo){ query.technologyNo = this.param.technologyNo}
            if(this.param.clientNumber){ query.clientNumber = this.param.clientNumber}
            if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
            if(this.param.workOrderNo){ query.workOrderNo = this.param.workOrderNo}
            if(this.param.result){ query.result = this.param.result}
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.startTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
            let data = await inspectionRecordFind(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
            this.tableInfo.forEach(item => {
                  item.img = this.cuttingStr(item.img)
                });
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            workCenter: '工作中心',
            problemLink: '检验环节',
            technologyNo: '产品品号',
            clientNumber: '客户编码',
            workOrderNo: '工单号码',
            deviceBarcode: '产品条码',
            result: '检查结果',
            jobNumber: '检查人',
            confirmor: '确认人',
            accessory: '检查表附件',
            img: '拍照记录',
            createTime: '检查日期',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await inspectionRecordDel({id:3})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // 导出excel
        async hExportExcel(e,row) {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          if(e == 'XZ'){
            query.id = row.id
        }else{
            query.page = 1
            query.limit = 10000
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
              if(this.param.problemLink){ query.problemLink = this.param.problemLink}
              if(this.param.technologyNo){ query.technologyNo = this.param.technologyNo}
              if(this.param.clientNumber){ query.clientNumber = this.param.clientNumber}
              if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
              if(this.param.workOrderNo){ query.workOrderNo = this.param.workOrderNo}
              if(this.param.result){ query.result = this.param.result}
            if(this.dateOptions) {
                if(this.dateOptions.length) {
                    query.startTime = this.dateOptions[0]
                    query.endTime = this.dateOptions[1]
                }
              }
        }
          let arr = await inspectionRecordFind(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list || !arr.data.list.length){
            this.loading = false
            return this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '制程检验记录', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = [] 
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              workCenter: item.workCenter,
              problemLink: item.problemLink,
              technologyNo: item.technologyNo,
              clientNumber: item.clientNumber,
              workOrderNo: item.workOrderNo,
              deviceBarcode: item.deviceBarcode,
              result: item.result,
              jobNumber: item.jobNumber,
              confirmor: item.confirmor,
              accessory: item.accessory,
              img: item.img,
              createTime: item.createTime,
            }
            arr1.push(obj)
          }) 
          return arr1
        },
        cancelSubmit(){
            this.param = {
                code: '',           
                content: '',      
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            const data = await configurationAdd(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.updForm = Object.assign({},row)
            this.showupd = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.configurationUpd()
                } else {
                    return false
                }
            })
        },
        async configurationUpd(){
            let query = Object.assign({},this.updForm)
            delete query.createTime
            delete query.updateTime
            const data = await configurationUpd(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        addInOrOut(){
            this.showAdd = true
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
